// 历史记录管理器
class HistoryManager {
    constructor() {
        this.storageKey = 'json_formatter_history';
        this.maxHistorySize = 50; // 最大保存50条记录
    }
    
    // 获取所有历史记录
    getHistory() {
        try {
            const history = localStorage.getItem(this.storageKey);
            return history ? JSON.parse(history) : [];
        } catch (error) {
            console.error('获取历史记录失败:', error);
            return [];
        }
    }
    
    // 保存历史记录
    saveHistory(history) {
        try {
            // 限制历史记录数量
            if (history.length > this.maxHistorySize) {
                history = history.slice(0, this.maxHistorySize);
            }
            localStorage.setItem(this.storageKey, JSON.stringify(history));
            return true;
        } catch (error) {
            console.error('保存历史记录失败:', error);
            return false;
        }
    }
    
    // 添加新记录
    addRecord(name, content) {
        const history = this.getHistory();
        const record = {
            id: Date.now().toString(),
            name: name.trim(),
            content: content,
            createdAt: new Date().toLocaleString(),
            size: new Blob([content]).size
        };
        
        // 检查是否有同名记录，如果有则覆盖
        const existingIndex = history.findIndex(item => item.name === name.trim());
        if (existingIndex >= 0) {
            history[existingIndex] = record;
        } else {
            history.unshift(record); // 添加到开头
        }
        
        return this.saveHistory(history) ? record : null;
    }
    
    // 删除记录
    deleteRecord(id) {
        const history = this.getHistory();
        const filteredHistory = history.filter(item => item.id !== id);
        return this.saveHistory(filteredHistory);
    }
    
    // 获取记录
    getRecord(id) {
        const history = this.getHistory();
        return history.find(item => item.id === id) || null;
    }
}

// JSON格式化器主应用
class JSONFormatter {
    constructor() {
        this.currentView = 'tree';
        this.jsonData = null;
        this.editorPanel = null;
        this.previewPanel = null;
        this.isDragging = false;
        this.historyManager = new HistoryManager();
        
        this.init();
    }

    init() {
        this.bindElements();
        this.bindEvents();
        this.setupResizer();
        this.updateLineNumbers();
        this.showPlaceholder();
        
        // 初始化时隐藏所有功能按钮
        this.formatBtn.style.display = 'none';
        this.minifyBtn.style.display = 'none';
        this.escapeBtn.style.display = 'none';
        this.unescapeBtn.style.display = 'none';
        this.smartFixBtn.style.display = 'none';
    }

    bindElements() {
        // 编辑器相关
        this.jsonInput = document.getElementById('json-input');
        this.lineNumbers = document.getElementById('line-numbers');
        this.lineCount = document.getElementById('line-count');
        this.charCount = document.getElementById('char-count');
        
        // 预览相关
        this.previewContent = document.getElementById('preview-content');
        this.tabBtns = document.querySelectorAll('.tab-btn');
        
        // 控制按钮
        this.formatBtn = document.getElementById('format-btn');
        this.minifyBtn = document.getElementById('minify-btn');
        this.smartFixBtn = document.getElementById('smart-fix-btn');
        this.escapeBtn = document.getElementById('escape-btn');
        this.unescapeBtn = document.getElementById('unescape-btn');
        this.saveBtn = document.getElementById('save-btn');
        this.loadBtn = document.getElementById('load-btn');
        
        // 状态栏
        this.statusText = document.getElementById('status-text');
        this.jsonInfo = document.getElementById('json-info');
        
        // 模态框
        this.errorModal = document.getElementById('error-modal');
        this.errorDetails = document.getElementById('error-details');
        this.repairModal = document.getElementById('repair-modal');
        this.repairInfo = document.getElementById('repair-info');
        this.diffStats = document.getElementById('diff-stats');
        this.originalContent = document.getElementById('original-content');
        this.repairedContent = document.getElementById('repaired-content');
        this.saveModal = document.getElementById('save-modal');
        this.loadModal = document.getElementById('load-modal');
        this.saveNameInput = document.getElementById('save-name');
        this.historyList = document.getElementById('history-list');
        
        // 面板
        this.editorPanel = document.querySelector('.editor-panel');
        this.previewPanel = document.querySelector('.preview-panel');
        this.resizer = document.getElementById('resizer');
    }

    bindEvents() {
        // 编辑器事件
        this.jsonInput.addEventListener('input', this.handleInputChange.bind(this));
        this.jsonInput.addEventListener('scroll', this.syncLineNumbers.bind(this));
        this.jsonInput.addEventListener('paste', this.handlePaste.bind(this));
        
        // 按钮事件
        this.formatBtn.addEventListener('click', this.formatJSON.bind(this));
        this.minifyBtn.addEventListener('click', this.minifyJSON.bind(this));
        this.smartFixBtn.addEventListener('click', this.smartFixJSON.bind(this));
        this.escapeBtn.addEventListener('click', this.escapeJSON.bind(this));
        this.unescapeBtn.addEventListener('click', this.unescapeJSON.bind(this));
        this.saveBtn.addEventListener('click', this.showSaveModal.bind(this));
        this.loadBtn.addEventListener('click', this.showLoadModal.bind(this));
        
        // 标签页切换
        this.tabBtns.forEach(btn => {
            btn.addEventListener('click', this.switchView.bind(this));
        });
        
        // 模态框事件
        this.setupModalEvents();
        

    }

    setupModalEvents() {
        // 错误模态框
        document.getElementById('error-close').addEventListener('click', () => {
            this.errorModal.style.display = 'none';
        });
        
        // 修复模态框
        document.getElementById('repair-close').addEventListener('click', () => {
            this.repairModal.style.display = 'none';
        });
        
        document.getElementById('cancel-repair').addEventListener('click', () => {
            this.repairModal.style.display = 'none';
        });
        
        document.getElementById('apply-repair').addEventListener('click', () => {
            this.applyRepair();
        });
        
        // 保存模态框
        document.getElementById('save-close').addEventListener('click', () => {
            this.saveModal.style.display = 'none';
        });
        
        document.getElementById('save-cancel').addEventListener('click', () => {
            this.saveModal.style.display = 'none';
        });
        
        document.getElementById('save-confirm').addEventListener('click', () => {
            this.saveHistory();
        });
        
        // 加载模态框
        document.getElementById('load-close').addEventListener('click', () => {
            this.loadModal.style.display = 'none';
        });
        
        // 保存名称输入框回车事件
        this.saveNameInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                this.saveHistory();
            }
        });
        
        // 点击外部关闭模态框
        window.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal')) {
                e.target.style.display = 'none';
            }
        });
    }

    setupResizer() {
        let startX = 0;
        let startLeftWidth = 0;
        
        this.resizer.addEventListener('mousedown', (e) => {
            this.isDragging = true;
            startX = e.clientX;
            startLeftWidth = this.editorPanel.offsetWidth;
            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('mouseup', handleMouseUp);
            document.body.style.cursor = 'col-resize';
        });
        
        const handleMouseMove = (e) => {
            if (!this.isDragging) return;
            
            const deltaX = e.clientX - startX;
            const newLeftWidth = startLeftWidth + deltaX;
            const containerWidth = this.editorPanel.parentElement.offsetWidth;
            const minWidth = 200;
            const maxWidth = containerWidth - 200;
            
            if (newLeftWidth >= minWidth && newLeftWidth <= maxWidth) {
                const leftPercentage = (newLeftWidth / containerWidth) * 100;
                const rightPercentage = 100 - leftPercentage;
                
                this.editorPanel.style.width = `${leftPercentage}%`;
                this.previewPanel.style.width = `${rightPercentage}%`;
            }
        };
        
        const handleMouseUp = () => {
            this.isDragging = false;
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
            document.body.style.cursor = 'default';
        };
    }

    handleInputChange() {
        this.updateLineNumbers();
        this.updateCharCount();
        this.updateFileSize();
        this.parseAndRender();
    }

    handlePaste(e) {
        setTimeout(() => {
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.parseAndRender();
        }, 10);
    }

    updateLineNumbers() {
        const lines = this.jsonInput.value.split('\n');
        const lineNumbersText = lines.map((_, index) => index + 1).join('\n');
        this.lineNumbers.textContent = lineNumbersText;
        this.lineCount.textContent = `${lines.length} 行`;
    }

    syncLineNumbers() {
        this.lineNumbers.scrollTop = this.jsonInput.scrollTop;
    }

    updateCharCount() {
        const count = this.jsonInput.value.length;
        this.charCount.textContent = `${count} 字符`;
    }

    updateFileSize() {
        const size = new Blob([this.jsonInput.value]).size;
        const sizeText = size < 1024 ? `${size} B` : 
                       size < 1024 * 1024 ? `${(size / 1024).toFixed(1)} KB` :
                       `${(size / (1024 * 1024)).toFixed(1)} MB`;
        this.jsonInfo.textContent = `${sizeText}`;
    }

    parseAndRender() {
        const content = this.jsonInput.value.trim();
        
        if (!content) {
            this.showPlaceholder();
            // 空内容时隐藏所有功能按钮
            this.formatBtn.style.display = 'none';
            this.minifyBtn.style.display = 'none';
            this.escapeBtn.style.display = 'none';
            this.unescapeBtn.style.display = 'none';
            this.smartFixBtn.style.display = 'none';
            return;
        }
        
        try {
            this.jsonData = JSON.parse(content);
            this.updateValidationStatus(true);
            this.renderCurrentView();
        } catch (error) {
            this.updateValidationStatus(false, error.message);
            this.showError(error.message);
        }
    }

    updateValidationStatus(isValid, errorMessage = '') {
        // 根据JSON解析状态控制按钮显示
        if (isValid) {
            // JSON解析正确时显示格式化、压缩、转义、去除转义按钮
            this.formatBtn.style.display = 'inline-block';
            this.minifyBtn.style.display = 'inline-block';
            this.escapeBtn.style.display = 'inline-block';
            this.unescapeBtn.style.display = 'inline-block';
            this.smartFixBtn.style.display = 'none';
        } else {
            // JSON解析错误时只显示智能修复按钮
            this.formatBtn.style.display = 'none';
            this.minifyBtn.style.display = 'none';
            this.escapeBtn.style.display = 'none';
            this.unescapeBtn.style.display = 'none';
            this.smartFixBtn.style.display = 'inline-block';
        }
    }

    showPlaceholder() {
        this.previewContent.innerHTML = '<div class="placeholder">请在左侧输入 JSON 数据</div>';
    }

    showError(errorMessage) {
        this.previewContent.innerHTML = `
            <div class="error-message">
                <strong>JSON 语法错误:</strong><br>
                ${this.escapeHtml(errorMessage)}
            </div>
        `;
    }

    renderCurrentView() {
        if (!this.jsonData) return;
        
        switch (this.currentView) {
            case 'tree':
                this.renderTreeView();
                break;
            case 'excel':
                this.renderExcelView();
                break;
            case 'yaml':
                this.renderYAMLView();
                break;
        }
    }



    renderTreeView() {
        const formatted = JSON.stringify(this.jsonData, null, 2);
        const treeHtml = this.createTreeFromJSON(formatted);
        this.previewContent.innerHTML = `<div class="json-tree">${treeHtml}</div>`;
        this.bindTreeEvents();
    }

    renderExcelView() {
        if (Array.isArray(this.jsonData) && this.jsonData.length > 0) {
            const excelHtml = this.createExcelView(this.jsonData);
            this.previewContent.innerHTML = excelHtml;
        } else {
            this.previewContent.innerHTML = '<div class="placeholder">Excel导出仅支持数组数据</div>';
        }
    }

    renderYAMLView() {
        try {
            const yamlString = this.jsonToYAML(this.jsonData);
            this.previewContent.innerHTML = `<pre class="yaml-content">${this.escapeHtml(yamlString)}</pre>`;
        } catch (error) {
            this.previewContent.innerHTML = '<div class="placeholder">YAML转换失败</div>';
        }
    }

    jsonToYAML(obj, indent = 0) {
        const spaces = '  '.repeat(indent);
        let yaml = '';

        if (obj === null) {
            return 'null';
        }

        if (typeof obj === 'boolean') {
            return obj.toString();
        }

        if (typeof obj === 'number') {
            return obj.toString();
        }

        if (typeof obj === 'string') {
            // 处理特殊字符串
            if (obj.includes('\n') || obj.includes('"') || obj.includes('\\')) {
                return `"${obj.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
            }
            return obj;
        }

        if (Array.isArray(obj)) {
            if (obj.length === 0) {
                return '[]';
            }
            
            for (let i = 0; i < obj.length; i++) {
                const item = obj[i];
                if (typeof item === 'object' && item !== null) {
                    if (Array.isArray(item)) {
                        yaml += `${spaces}- ${this.jsonToYAML(item, indent + 1)}\n`;
                    } else {
                        const itemYaml = this.jsonToYAML(item, indent + 1);
                        const lines = itemYaml.split('\n');
                        yaml += `${spaces}- ${lines[0]}\n`;
                        for (let j = 1; j < lines.length; j++) {
                            yaml += `${spaces}  ${lines[j]}\n`;
                        }
                    }
                } else {
                    yaml += `${spaces}- ${this.jsonToYAML(item, indent + 1)}\n`;
                }
            }
            return yaml.trimRight();
        }

        if (typeof obj === 'object') {
            const keys = Object.keys(obj);
            if (keys.length === 0) {
                return '{}';
            }

            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                const value = obj[key];
                
                // 处理键名
                let keyStr = key;
                if (key.includes(' ') || key.includes(':') || key.includes('-')) {
                    keyStr = `"${key}"`;
                }

                if (typeof value === 'object' && value !== null) {
                    if (Array.isArray(value)) {
                        if (value.length === 0) {
                            yaml += `${spaces}${keyStr}: []\n`;
                        } else {
                            yaml += `${spaces}${keyStr}:\n`;
                            yaml += this.jsonToYAML(value, indent + 1) + '\n';
                        }
                    } else {
                        if (Object.keys(value).length === 0) {
                            yaml += `${spaces}${keyStr}: {}\n`;
                        } else {
                            yaml += `${spaces}${keyStr}:\n`;
                            yaml += this.jsonToYAML(value, indent + 1) + '\n';
                        }
                    }
                } else {
                    yaml += `${spaces}${keyStr}: ${this.jsonToYAML(value, indent + 1)}\n`;
                }
            }
            return yaml.trimRight();
        }

        return '';
    }

    highlightJSON(json) {
        return json
            .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, 
                (match) => {
                    let cls = 'json-number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) {
                            cls = 'json-key';
                        } else {
                            cls = 'json-string';
                        }
                    } else if (/true|false/.test(match)) {
                        cls = 'json-boolean';
                    } else if (/null/.test(match)) {
                        cls = 'json-null';
                    }
                    return `<span class="${cls}">${match}</span>`;
                })
            .replace(/([{}[\],])/g, '<span class="json-punctuation">$1</span>');
    }

    createTreeFromJSON(jsonString) {
        const lines = jsonString.split('\n');
        let html = '';
        let stack = [];
        
        lines.forEach((line, index) => {
            const trimmedLine = line.trim();
            if (!trimmedLine) return;
            
            // 计算当前行的缩进级别
            const indent = line.length - line.trimStart().length;
            const indentLevel = indent / 2;
            
            // 更精确地检查是否是对象或数组的开始
            const endsWithOpenBrace = trimmedLine.endsWith('{');
            const endsWithOpenBracket = trimmedLine.endsWith('[');
            const isExpandableStart = endsWithOpenBrace || endsWithOpenBracket;
            
            // 检查是否是结束标记
            const isClosing = trimmedLine === '}' || trimmedLine === '},' || 
                             trimmedLine === ']' || trimmedLine === '],';
            
            // 高亮处理
            const highlightedLine = this.highlightJSON(trimmedLine);
            
            if (isExpandableStart) {
                // 开始一个新的可折叠节点
                html += `
                    <div class="tree-node">
                        <div class="tree-item" style="margin-left: ${indentLevel * 20}px;">
                            <button class="tree-toggle">▼</button>
                            <span class="tree-content">${highlightedLine}</span>
                        </div>
                        <div class="tree-children">
                `;
                stack.push('open');
            } else if (isClosing && stack.length > 0) {
                // 结束当前节点
                html += `
                            <div class="tree-item" style="margin-left: ${indentLevel * 20}px;">
                                <span class="tree-toggle"></span>
                                <span class="tree-content">${highlightedLine}</span>
                            </div>
                        </div>
                    </div>
                `;
                stack.pop();
            } else {
                // 普通行
                html += `
                    <div class="tree-item" style="margin-left: ${indentLevel * 20}px;">
                        <span class="tree-toggle"></span>
                        <span class="tree-content">${highlightedLine}</span>
                    </div>
                `;
            }
        });
        
        return html;
    }

    createExcelView(data) {
        if (!Array.isArray(data) || data.length === 0) {
            return '<div class="placeholder">无数据</div>';
        }
        
        // 获取所有可能的列
        const columns = new Set();
        data.forEach(item => {
            if (typeof item === 'object' && item !== null) {
                Object.keys(item).forEach(key => columns.add(key));
            }
        });
        
        const columnArray = Array.from(columns);
        
        if (columnArray.length === 0) {
            return '<div class="placeholder">数据不适合Excel导出</div>';
        }

        // 创建Excel预览表格
        const headerHtml = columnArray.map(col => `<th>${this.escapeHtml(col)}</th>`).join('');
        const rowsHtml = data.map((item, index) => {
            const cells = columnArray.map(col => {
                const value = item && typeof item === 'object' ? item[col] : '';
                return `<td>${this.escapeHtml(this.formatExcelValue(value))}</td>`;
            }).join('');
            return `<tr>${cells}</tr>`;
        }).join('');
        
        return `
            <div class="excel-container">
                <div class="excel-header">
                    <div class="excel-info">
                        <h3>Excel 导出预览</h3>
                        <span class="excel-stats">数据行数: ${data.length} | 列数: ${columnArray.length}</span>
                    </div>
                    <div class="excel-actions">
                        <button class="btn btn-primary" onclick="app.downloadExcel()">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M3 15v4c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2v-4"/>
                                <polyline points="8,15 12,19 16,15"/>
                                <line x1="12" y1="19" x2="12" y2="3"/>
                            </svg>
                            下载 Excel
                        </button>
                        <button class="btn btn-secondary" onclick="app.copyExcelData()">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                            </svg>
                            复制数据
                        </button>
                    </div>
                </div>
                <div class="excel-table-container">
                    <table class="json-table excel-table">
                        <thead>
                            <tr>${headerHtml}</tr>
                        </thead>
                        <tbody>
                            ${rowsHtml}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    }

    bindTreeEvents() {
        const toggles = this.previewContent.querySelectorAll('.tree-toggle');
        toggles.forEach(toggle => {
            // 只为实际的按钮添加事件监听器
            if (toggle.tagName === 'BUTTON') {
                toggle.addEventListener('click', (e) => {
                    const node = e.target.closest('.tree-node');
                    if (node) {
                        const isCollapsed = node.classList.contains('tree-collapsed');
                        const treeContent = node.querySelector('.tree-content');
                        
                        if (isCollapsed) {
                            // 展开：恢复原始内容
                            node.classList.remove('tree-collapsed');
                            e.target.textContent = '▼';
                            if (treeContent.dataset.originalContent) {
                                treeContent.innerHTML = treeContent.dataset.originalContent;
                            }
                        } else {
                            // 收缩：保存原始内容并显示简化版本
                            node.classList.add('tree-collapsed');
                            e.target.textContent = '▶';
                            
                            // 保存原始内容
                            if (!treeContent.dataset.originalContent) {
                                treeContent.dataset.originalContent = treeContent.innerHTML;
                            }
                            
                            // 确定是对象还是数组
                            const originalText = treeContent.textContent || treeContent.innerText;
                            const isArray = originalText.includes('[');
                            const isObject = originalText.includes('{');
                            
                            if (isArray) {
                                // 创建简化的数组显示
                                const keyPart = originalText.split('[')[0];
                                const highlighted = this.highlightJSON(keyPart + '[...]');
                                treeContent.innerHTML = highlighted;
                            } else if (isObject) {
                                // 创建简化的对象显示
                                const keyPart = originalText.split('{')[0];
                                const highlighted = this.highlightJSON(keyPart + '{...}');
                                treeContent.innerHTML = highlighted;
                            }
                        }
                    }
                });
            }
        });
    }

    getValueClass(value) {
        if (typeof value === 'string') return 'json-string';
        if (typeof value === 'number') return 'json-number';
        if (typeof value === 'boolean') return 'json-boolean';
        if (value === null) return 'json-null';
        return '';
    }

    formatValue(value) {
        if (typeof value === 'string') {
            return `"${this.escapeHtml(value)}"`;
        }
        if (value === null) return 'null';
        return String(value);
    }

    formatExcelValue(value) {
        if (value === null || value === undefined) return '';
        if (typeof value === 'object') {
            return JSON.stringify(value);
        }
        return String(value);
    }

    downloadExcel() {
        if (!Array.isArray(this.jsonData) || this.jsonData.length === 0) {
            this.showMessage('没有可导出的数据');
            return;
        }

        // 获取所有可能的列
        const columns = new Set();
        this.jsonData.forEach(item => {
            if (typeof item === 'object' && item !== null) {
                Object.keys(item).forEach(key => columns.add(key));
            }
        });
        
        const columnArray = Array.from(columns);
        
        // 创建CSV格式的数据（Excel可以打开）
        const csvRows = [];
        
        // 添加表头
        csvRows.push(columnArray.map(col => `"${col}"`).join(','));
        
        // 添加数据行
        this.jsonData.forEach(item => {
            const row = columnArray.map(col => {
                const value = item && typeof item === 'object' ? item[col] : '';
                const formattedValue = this.formatExcelValue(value);
                return `"${formattedValue.replace(/"/g, '""')}"`;
            });
            csvRows.push(row.join(','));
        });
        
        // 创建Blob并下载
        const csvContent = csvRows.join('\n');
        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
        
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `json_data_${new Date().toISOString().slice(0, 10)}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.showMessage('Excel文件下载成功');
    }

    copyExcelData() {
        if (!Array.isArray(this.jsonData) || this.jsonData.length === 0) {
            this.showMessage('没有可复制的数据');
            return;
        }

        // 获取所有可能的列
        const columns = new Set();
        this.jsonData.forEach(item => {
            if (typeof item === 'object' && item !== null) {
                Object.keys(item).forEach(key => columns.add(key));
            }
        });
        
        const columnArray = Array.from(columns);
        
        // 创建制表符分隔的数据（适合粘贴到Excel）
        const rows = [];
        
        // 添加表头
        rows.push(columnArray.join('\t'));
        
        // 添加数据行
        this.jsonData.forEach(item => {
            const row = columnArray.map(col => {
                const value = item && typeof item === 'object' ? item[col] : '';
                return this.formatExcelValue(value);
            });
            rows.push(row.join('\t'));
        });
        
        // 复制到剪贴板
        const textContent = rows.join('\n');
        
        navigator.clipboard.writeText(textContent).then(() => {
            this.showMessage('数据已复制到剪贴板，可直接粘贴到Excel');
        }).catch(err => {
            // 降级处理
            const textArea = document.createElement('textarea');
            textArea.value = textContent;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            this.showMessage('数据已复制到剪贴板');
        });
    }

    switchView(e) {
        const view = e.target.getAttribute('data-view');
        if (view === this.currentView) return;
        
        this.currentView = view;
        
        // 更新标签页状态
        this.tabBtns.forEach(btn => btn.classList.remove('active'));
        e.target.classList.add('active');
        
        // 重新渲染
        this.renderCurrentView();
    }

    formatJSON() {
        const content = this.jsonInput.value.trim();
        if (!content) {
            this.showMessage('请先输入 JSON 数据');
            return;
        }
        
        try {
            const parsed = JSON.parse(content);
            const formatted = JSON.stringify(parsed, null, 2);
            this.jsonInput.value = formatted;
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.parseAndRender();
            this.showMessage('JSON 格式化完成');
        } catch (error) {
            this.showErrorModal(error.message);
        }
    }

    minifyJSON() {
        const content = this.jsonInput.value.trim();
        if (!content) {
            this.showMessage('请先输入 JSON 数据');
            return;
        }
        
        try {
            const parsed = JSON.parse(content);
            const minified = JSON.stringify(parsed);
            this.jsonInput.value = minified;
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.parseAndRender();
            this.showMessage('JSON 压缩完成');
        } catch (error) {
            this.showErrorModal(error.message);
        }
    }

    escapeJSON() {
        const content = this.jsonInput.value.trim();
        if (!content) {
            this.showMessage('请先输入内容');
            return;
        }
        
        try {
            // 首先验证是否为有效的JSON
            JSON.parse(content);
            
            // 将JSON内容转换为转义的字符串
            const escaped = JSON.stringify(content);
            this.jsonInput.value = escaped;
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.parseAndRender();
            this.showMessage('JSON转义完成');
        } catch (error) {
            // 如果不是有效JSON，就当作普通字符串处理
            const escaped = JSON.stringify(content);
            this.jsonInput.value = escaped;
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.parseAndRender();
            this.showMessage('字符串转义完成');
        }
    }

    unescapeJSON() {
        const content = this.jsonInput.value.trim();
        if (!content) {
            this.showMessage('请先输入内容');
            return;
        }
        
        try {
            // 尝试解析转义的字符串
            const unescaped = JSON.parse(content);
            
            // 如果解析结果是字符串，直接使用
            if (typeof unescaped === 'string') {
                this.jsonInput.value = unescaped;
            } else {
                // 如果解析结果是对象，格式化输出
                this.jsonInput.value = JSON.stringify(unescaped, null, 2);
            }
            
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.parseAndRender();
            this.showMessage('去转义完成');
        } catch (error) {
            this.showErrorModal('去转义失败: 内容不是有效的转义字符串\n' + error.message);
        }
    }

    // 智能修复JSON格式
    smartFixJSON() {
        const content = this.jsonInput.value.trim();
        if (!content) {
            this.showMessage('请先输入 JSON 数据');
            return;
        }
        
        try {
            // 首先尝试直接解析
            JSON.parse(content);
            this.showMessage('JSON 格式正确，无需修复');
            return;
        } catch (error) {
            // JSON有错误，使用 jsonrepair 库进行智能修复
            this.performSmartRepair(content);
        }
    }

    // 执行智能修复
    performSmartRepair(originalContent) {
        try {
            // 检查 jsonrepair 库是否可用
            if (typeof JSONRepair === 'undefined' || typeof JSONRepair.jsonrepair !== 'function') {
                this.showErrorModal('智能修复库未加载，请刷新页面重试');
                return;
            }

            // 使用 jsonrepair 库修复 JSON
            const repairedContent = JSONRepair.jsonrepair(originalContent);
            
            // 验证修复后的内容是否为有效JSON
            JSON.parse(repairedContent);
            
            // 显示修复结果
            this.showRepairResult(originalContent, repairedContent, true);
            
        } catch (repairError) {
            console.error('JSON修复失败:', repairError);
            
            // 如果 jsonrepair 失败，尝试基础修复
            const basicRepaired = this.attemptBasicRepair(originalContent);
            if (basicRepaired) {
                this.showRepairResult(originalContent, basicRepaired, false);
            } else {
                this.showErrorModal(`智能修复失败: ${repairError.message}`);
            }
        }
    }

    // 显示修复结果
    showRepairResult(originalContent, repairedContent, isAdvancedRepair = true) {
        // 设置修复信息
        const repairType = isAdvancedRepair ? '高级智能修复' : '基础修复';
        const repairStatus = isAdvancedRepair ? 'success' : 'warning';
        
        this.repairInfo.className = `repair-info ${repairStatus}`;
        this.repairInfo.innerHTML = '';
        
        // 生成差异对比
        const diffResult = this.generateDiff(originalContent, repairedContent);
        
        // 显示差异统计
        this.showDiffStats(diffResult.stats);
        
        // 显示带高亮的原始内容和修复后的内容
        this.originalContent.innerHTML = diffResult.originalHighlighted;
        this.repairedContent.innerHTML = diffResult.repairedHighlighted;
        
        // 存储修复后的内容供应用使用
        this.currentRepairedContent = repairedContent;
        
        // 显示模态框
        this.repairModal.style.display = 'block';
    }

    // 应用修复结果
    applyRepair() {
        if (this.currentRepairedContent) {
            this.jsonInput.value = this.currentRepairedContent;
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.parseAndRender();
            this.repairModal.style.display = 'none';
            this.showMessage('修复已应用');
        }
    }

    // 生成差异对比
    generateDiff(original, repaired) {
        const stats = {
            changed: 0,
            indices: []
        };

        // 分析修复类型
        const originalLines = original.split('\n');
        const repairedLines = repaired.split('\n');
        
        let originalHighlighted = '';
        let repairedHighlighted = '';
        
        // 逐行比较
        const maxLines = Math.max(originalLines.length, repairedLines.length);
        
        for (let i = 0; i < maxLines; i++) {
            const originalLine = originalLines[i] || '';
            const repairedLine = repairedLines[i] || '';
            const lineNumber = i + 1; // 行号从1开始
            
            if (originalLine !== repairedLine) {
                // 检测注释移除
                if (this.isCommentLine(originalLine) && !this.isCommentLine(repairedLine)) {
                    stats.changed++;
                    stats.indices.push(lineNumber);
                    originalHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${this.highlightComment(originalLine)}\n`;
                    repairedHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${repairedLine}\n`;
                    continue;
                }
                
                // 检测引号修复
                const quoteDiff = this.detectQuoteChanges(originalLine, repairedLine);
                if (quoteDiff.changed) {
                    stats.changed += quoteDiff.count;
                    stats.indices.push(lineNumber);
                    originalHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${quoteDiff.originalHighlighted}\n`;
                    repairedHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${quoteDiff.repairedHighlighted}\n`;
                    continue;
                }
                
                // 检测逗号修复
                const commaDiff = this.detectCommaChanges(originalLine, repairedLine);
                if (commaDiff.changed) {
                    stats.changed += commaDiff.count;
                    stats.indices.push(lineNumber);
                    originalHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${commaDiff.originalHighlighted}\n`;
                    repairedHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${commaDiff.repairedHighlighted}\n`;
                    continue;
                }
                
                // 检测未引用属性名修复
                const propertyDiff = this.detectPropertyChanges(originalLine, repairedLine);
                if (propertyDiff.changed) {
                    stats.changed += propertyDiff.count;
                    stats.indices.push(lineNumber);
                    originalHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${propertyDiff.originalHighlighted}\n`;
                    repairedHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${propertyDiff.repairedHighlighted}\n`;
                    continue;
                }
                
                // 其他变更
                stats.changed++;
                stats.indices.push(lineNumber);
                originalHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${this.highlightChanged(originalLine)}\n`;
                repairedHighlighted += `<span class="line-number line-number-changed">${lineNumber}</span>${this.highlightChanged(repairedLine)}\n`;
            } else {
                originalHighlighted += `<span class="line-number">${lineNumber}</span>${originalLine}\n`;
                repairedHighlighted += `<span class="line-number">${lineNumber}</span>${repairedLine}\n`;
            }
        }
        
        return {
            stats,
            originalHighlighted: originalHighlighted.trim(),
            repairedHighlighted: repairedHighlighted.trim()
        };
    }

    // 显示差异统计
    showDiffStats(stats) {
        if (stats.changed > 0) {
            document.getElementById('changed-count').textContent = `变更: ${stats.changed}`;
            this.diffStats.style.display = 'flex';
        } else {
            this.diffStats.style.display = 'none';
        }
    }

    // 检测是否为注释行
    isCommentLine(line) {
        const trimmed = line.trim();
        return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.includes('*/');
    }

    // 高亮注释
    highlightComment(line) {
        return line.replace(/(\/\/.*$|\/\*[\s\S]*?\*\/)/g, '<span class="diff-highlight comment-removed">$1</span>');
    }

    // 检测引号变化
    detectQuoteChanges(original, repaired) {
        const changes = {
            changed: false,
            count: 0,
            originalHighlighted: original,
            repairedHighlighted: repaired
        };

        // 检测单引号转双引号
        const singleQuoteRegex = /'([^']*)'/g;
        let match;
        let count = 0;
        
        while ((match = singleQuoteRegex.exec(original)) !== null) {
            count++;
        }
        
        if (count > 0) {
            changes.changed = true;
            changes.count = count;
            changes.originalHighlighted = original.replace(/'([^']*)'/g, '<span class="diff-highlight quote-fixed">\'$1\'</span>');
            changes.repairedHighlighted = repaired.replace(/"([^"]*)"/g, '<span class="diff-highlight quote-fixed">"$1"</span>');
        }

        return changes;
    }

    // 检测逗号变化
    detectCommaChanges(original, repaired) {
        const changes = {
            changed: false,
            count: 0,
            originalHighlighted: original,
            repairedHighlighted: repaired
        };

        // 检测尾随逗号
        const trailingCommaRegex = /,(\s*[}\]])/g;
        let match;
        let count = 0;
        
        while ((match = trailingCommaRegex.exec(original)) !== null) {
            count++;
        }
        
        if (count > 0) {
            changes.changed = true;
            changes.count = count;
            changes.originalHighlighted = original.replace(/,(\s*[}\]])/g, '<span class="diff-highlight comma-fixed">,$1</span>');
            changes.repairedHighlighted = repaired;
        }

        return changes;
    }

    // 检测属性名变化
    detectPropertyChanges(original, repaired) {
        const changes = {
            changed: false,
            count: 0,
            originalHighlighted: original,
            repairedHighlighted: repaired
        };

        // 检测未引用的属性名
        const unquotedPropertyRegex = /(\s*)(\w+)(\s*):/g;
        let match;
        let count = 0;
        
        while ((match = unquotedPropertyRegex.exec(original)) !== null) {
            count++;
        }
        
        if (count > 0) {
            changes.changed = true;
            changes.count = count;
            changes.originalHighlighted = original.replace(/(\s*)(\w+)(\s*):/g, '$1<span class="diff-highlight changed">$2</span>$3:');
            changes.repairedHighlighted = repaired.replace(/(\s*)"(\w+)"(\s*):/g, '$1<span class="diff-highlight changed">"$2"</span>$3:');
        }

        return changes;
    }

    // 高亮变更的行
    highlightChanged(line) {
        return `<span class="diff-highlight changed">${this.escapeHtml(line)}</span>`;
    }

    // 基础修复方法（备用）
    attemptBasicRepair(content) {
        try {
            // 1. 移除注释
            content = this.removeComments(content);
            
            // 2. 修复常见的语法错误
            content = this.fixCommonErrors(content);
            
            // 3. 尝试解析验证
            JSON.parse(content);
            return content;
        } catch (error) {
            console.error('基础JSON修复失败:', error);
            return null;
        }
    }

    // 移除注释
    removeComments(content) {
        // 移除单行注释 //
        content = content.replace(/\/\/.*$/gm, '');
        // 移除多行注释 /* */
        content = content.replace(/\/\*[\s\S]*?\*\//g, '');
        return content;
    }

    // 修复常见错误
    fixCommonErrors(content) {
        // 1. 修复单引号为双引号
        content = content.replace(/'/g, '"');
        
        // 2. 修复未引用的属性名
        content = content.replace(/(\s*)(\w+)(\s*):/g, '$1"$2"$3:');
        
        // 3. 移除尾随逗号
        content = content.replace(/,(\s*[}\]])/g, '$1');
        
        // 4. 修复缺失的引号
        content = content.replace(/:\s*([^"{\[\d][^,}\]]*[^"\s,}\]])/g, ': "$1"');
        
        // 5. 修复布尔值和null
        content = content.replace(/:\s*"true"/g, ': true');
        content = content.replace(/:\s*"false"/g, ': false');
        content = content.replace(/:\s*"null"/g, ': null');
        
        return content;
    }

    showMessage(message) {
        this.statusText.textContent = message;
        setTimeout(() => {
            this.statusText.textContent = '就绪';
        }, 3000);
    }
    
    // 显示保存模态框
    showSaveModal() {
        const content = this.jsonInput.value.trim();
        if (!content) {
            this.showMessage('请先输入 JSON 数据');
            return;
        }
        
        // 验证JSON格式
        try {
            JSON.parse(content);
        } catch (error) {
            this.showMessage('请先修复 JSON 格式错误');
            return;
        }
        
        this.saveNameInput.value = '';
        this.saveModal.style.display = 'block';
        this.saveNameInput.focus();
    }
    
    // 显示加载模态框
    showLoadModal() {
        this.renderHistoryList();
        this.loadModal.style.display = 'block';
    }
    
    // 保存历史记录
    saveHistory() {
        const name = this.saveNameInput.value.trim();
        if (!name) {
            this.showMessage('请输入保存名称');
            return;
        }
        
        const content = this.jsonInput.value.trim();
        const record = this.historyManager.addRecord(name, content);
        
        if (record) {
            this.saveModal.style.display = 'none';
            this.showMessage(`"${name}" 保存成功`);
        } else {
            this.showMessage('保存失败，请重试');
        }
    }
    
    // 渲染历史记录列表
    renderHistoryList() {
        const history = this.historyManager.getHistory();
        
        if (history.length === 0) {
            this.historyList.innerHTML = '<div class="empty-history">暂无历史记录</div>';
            return;
        }
        
        const historyHTML = history.map(record => {
            const sizeText = record.size < 1024 ? `${record.size} B` : 
                           record.size < 1024 * 1024 ? `${(record.size / 1024).toFixed(1)} KB` :
                           `${(record.size / (1024 * 1024)).toFixed(1)} MB`;
            
            return `
                <div class="history-item">
                    <div class="history-info">
                        <div class="history-name">${this.escapeHtml(record.name)}</div>
                        <div class="history-meta">
                            <span>保存时间: ${record.createdAt}</span>
                            <span>大小: ${sizeText}</span>
                        </div>
                    </div>
                    <div class="history-actions">
                        <button class="btn-small btn-load" onclick="app.loadHistory('${record.id}')">加载</button>
                        <button class="btn-small btn-delete" onclick="app.deleteHistory('${record.id}')">删除</button>
                    </div>
                </div>
            `;
        }).join('');
        
        this.historyList.innerHTML = historyHTML;
    }
    
    // 加载历史记录
    loadHistory(id) {
        const record = this.historyManager.getRecord(id);
        if (record) {
            this.jsonInput.value = record.content;
            this.parseAndRender();
            this.updateLineNumbers();
            this.updateCharCount();
            this.updateFileSize();
            this.loadModal.style.display = 'none';
            this.showMessage(`"${record.name}" 加载成功`);
        } else {
            this.showMessage('加载失败，记录不存在');
        }
    }
    
    // 删除历史记录
    deleteHistory(id) {
        if (confirm('确定要删除这条记录吗？')) {
            if (this.historyManager.deleteRecord(id)) {
                this.renderHistoryList();
                this.showMessage('删除成功');
            } else {
                this.showMessage('删除失败');
            }
        }
    }

    showErrorModal(message) {
        this.errorDetails.textContent = message;
        this.errorModal.style.display = 'block';
    }



    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 初始化应用
let app; // 全局变量供HTML事件使用

document.addEventListener('DOMContentLoaded', () => {
    app = new JSONFormatter();
});



 